package com.ruoyi.web.controller.api.webapp;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.dto.WAppSysUserDto;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/webapp/system/user")
public class WAppSysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;


    /**
     * 根据用户编号获取详细信息
     */
    @Anonymous
    @GetMapping(value = {  "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = true) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
        }
        return ajax;
    }


    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody WAppSysUserDto user)
    {

        int rows = userService.wappUpdateUser(user);
        //更新缓存
        if(rows > 0) {
            SysUser existSysUser = userService.selectUserById(user.getUserId());
            LoginUser loginUser = getLoginUser();
            SysUser currentUser = loginUser.getUser();
            currentUser.setNickName(existSysUser.getNickName());
            currentUser.setAvatar(existSysUser.getAvatar());
            // 更新缓存用户信息
            tokenService.setLoginUser(loginUser);
        }
        return toAjax(rows);
    }

}